<template>
  <el-dialog v-model="drawerVisible" :title="`${drawerProps.title}`" draggable width="1040px">
    <el-form
      ref="ruleFormRef"
      :disabled="drawerProps.isView"
      :hide-required-asterisk="drawerProps.isView"
      :model="drawerProps.row"
      :rules="rules"
      label-suffix=" :"
      label-width="110px"
    >
      {{ drawerProps.status }}
      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="入库编号" prop="code">
            <el-input v-model="drawerProps.row!.code" clearable disabled placeholder="请填写入库编号"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row
        v-show="userType == 'Admin' || drawerProps.status == 'Created' || drawerProps.title == '编辑工单' || drawerProps.isView"
        :gutter="20"
      >
        <el-col :span="12">
          <el-form-item label="来源日期" prop="sourceDate">
            <el-date-picker v-model="drawerProps.row!.sourceDate" placeholder="选择年月日" type="date"></el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="来办日期" prop="processingDate">
            <el-date-picker v-model="drawerProps.row!.processingDate" placeholder="选择年月日" type="date"></el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="签收日期" prop="signingDate">
            <el-date-picker v-model="drawerProps.row!.signingDate" placeholder="选择年月日" type="date"></el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="来源" prop="source">
            <el-input v-model="drawerProps.row!.source" clearable placeholder="请填写来源"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="企业号" prop="enterpriseId">
            <el-input v-model="drawerProps.row!.source" clearable placeholder="请填写企业号"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="客户名称" prop="customerName">
            <el-input v-model="drawerProps.row!.customerName" clearable placeholder="请填写客户名称"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="客户年龄" prop="customerAge">
            <el-input v-model="drawerProps.row!.customerAge" clearable placeholder="请填写客户年龄"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="客户芝麻分" prop="sesameScore">
            <el-input v-model.number="drawerProps.row!.sesameScore" clearable placeholder="请填写客户芝麻分"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="平台" prop="platform">
            <el-input v-model="drawerProps.row!.platform" clearable placeholder="请填写平台"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="第几台" prop="deviceNumber">
            <el-input v-model="drawerProps.row!.deviceNumber" clearable placeholder="请填写第几台"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="型号颜色" prop="modelColor">
            <el-input v-model="drawerProps.row!.modelColor" clearable placeholder="请填写型号颜色"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="垫付金额" prop="advanceAmount">
            <el-input v-model="drawerProps.row!.advanceAmount" clearable placeholder="请填写垫付金额"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="其他" prop="others">
            <el-input v-model="drawerProps.row!.others" clearable placeholder="请填写其他" type="textarea"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col v-show="userType == 'Admin' || drawerProps.status == 'PendingReceipt' || drawerProps.isView" :span="12">
          <el-form-item label="收货快递单号" prop="customerReceiptTracking">
            <el-input v-model="drawerProps.row!.customerReceiptTracking" clearable placeholder="请填写收货快递单号"></el-input>
          </el-form-item>
        </el-col>
        <el-col v-show="userType == 'Admin' || drawerProps.status == 'InTransit' || drawerProps.isView" :span="12">
          <el-form-item label="寄出快递单号" prop="customerSendTracking">
            <el-input v-model="drawerProps.row!.customerSendTracking" clearable placeholder="请填写寄出快递单号"></el-input>
          </el-form-item>
        </el-col>
        <el-col v-show="userType == 'Admin' || drawerProps.isView" :span="12">
          <el-form-item label="快递费" prop="shippingFee">
            <el-input v-model="drawerProps.row!.shippingFee" clearable placeholder="请填写快递费"></el-input>
          </el-form-item>
        </el-col>
        <el-col v-show="userType == 'Admin' || drawerProps.status == 'unCompleted' || drawerProps.isView" :span="12">
          <el-form-item label="回款金额" prop="repaymentAmount">
            <el-input
              v-model="drawerProps.row!.repaymentAmount"
              :formatter="formatter"
              clearable
              placeholder="请填写回款金额"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col v-show="userType == 'Admin' || drawerProps.isView" :span="12">
          <el-form-item label="共回款金额" prop="totalRepayment">
            <el-input v-model="drawerProps.row!.totalRepayment" clearable placeholder="请填写共回款金额"></el-input>
          </el-form-item>
        </el-col>
        <el-col v-show="userType == 'Admin' || drawerProps.isView" :span="12">
          <el-form-item label=" 商家回收金额" prop="merchantRecoveryAmount">
            <el-input v-model="drawerProps.row!.merchantRecoveryAmount" clearable placeholder="请填写商家回收金额"></el-input>
          </el-form-item>
        </el-col>
        <el-col v-show="userType == 'Admin' || drawerProps.isView" :span="12">
          <el-form-item label="余额" prop="balance">
            <el-input v-model="drawerProps.row!.balance" clearable placeholder="请填写余额"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <el-button @click="drawerVisible = false">取消</el-button>
      <el-button v-show="!drawerProps.isView" type="primary" @click="handleSubmit">确定 </el-button>
    </template>
  </el-dialog>
</template>

<script lang="ts" name="UserDrawer" setup>
import { ref, reactive, computed } from "vue";
import { genderType } from "@/utils/dict";
import { ElMessage, FormInstance } from "element-plus";
import { User } from "@/api/interface";
import { format } from "date-fns";
import { getCode } from "@/api/modules/list";
import { useUserStore } from "@/stores/modules/user";

const rules = reactive({
  sourceDate: [{ required: true, message: "请选择来源日期", trigger: "change" }],
  processingDate: [{ required: true, message: "请选择来办日期", trigger: "change" }],
  // 保留原有规则
  username: [{ required: true, message: "请填写用户姓名" }],
  phone: [{ required: true, message: "请填写用户电话" }]
});

const formatter = value => {
  if (!value) return "";

  // 确保是数字
  const numberValue = typeof value === "string" ? parseFloat(value) : value;

  if (isNaN(numberValue)) return "";

  // 保留两位小数并添加千分位
  return numberValue.toFixed(2).replace(/\B(?=(\d{3})+(?!\d))/g, ",");
};

interface DrawerProps {
  title: string;
  status?: string;
  isView: boolean;
  row: Partial<User.ResUserList>;
  api?: (params: any) => Promise<any>;
  getTableList?: () => void;
}

const drawerVisible = ref(false);
const drawerProps = ref<DrawerProps>({
  isView: false,
  title: "",
  row: {}
});
const username = computed(() => userStore.userInfo.name);
// 接收父组件传过来的参数
const acceptParams = (params: DrawerProps) => {
  drawerProps.value = params;
  // drawerProps.value.row.signingDate= format(new Date(), "yyyy-MM-dd")
  // drawerProps.value.row.sourceDate= format(params.row.sourceDate, "yyyy-MM-dd")
  // drawerProps.value.row.processingDate= format(params.row.processingDate, "yyyy-MM-dd")
  // drawerProps.value.row.processingDate= format(new Date(), "yyyy-MM-dd")
  if (params.title === "新增工单") {
    getCode({}).then(res => {
      drawerProps.value.row.code = res.data.code;
      drawerProps.value.row.createdBy = username;
    });
  }
  drawerVisible.value = true;
};
const userStore = useUserStore();
const userType = computed(() => userStore.userInfo.user_type);
// 提交数据（新增/编辑）
const ruleFormRef = ref<FormInstance>();
const handleSubmit = () => {
  ruleFormRef.value!.validate(async valid => {
    if (!valid) return;
    try {
      drawerProps.value.row.sourceDate = format(drawerProps.value.row.sourceDate, "yyyy-MM-dd");
      drawerProps.value.row.processingDate = format(drawerProps.value.row.processingDate, "yyyy-MM-dd");
      drawerProps.value.row.signingDate = format(drawerProps.value.row.signingDate, "yyyy-MM-dd");
      await drawerProps.value.api!(drawerProps.value.row);
      ElMessage.success({ message: `${drawerProps.value.title}工单成功！` });
      drawerProps.value.getTableList!();
      drawerVisible.value = false;
    } catch (error) {
      console.log(error);
    }
  });
};

defineExpose({
  acceptParams
});
</script>
<style lang="scss"></style>
